package com.gx.smart.lib.http.api;

import com.casic.gx.grpc.qrcodepass.QRCodePassReq;
import com.casic.gx.grpc.qrcodepass.QRCodePassResp;
import com.casic.gx.grpc.qrcodepass.ServiceQRCodePassGrpc;
import com.casic.gx.grpc.qrcodepass.UserInfo;
import com.gx.smart.lib.http.api.asynctask.CallBack;
import com.gx.smart.lib.http.api.asynctask.GrpcAsyncTask;
import com.gx.smart.lib.http.api.config.ApiConfig;
import com.gx.smart.lib_http.BuildConfig;
import com.orhanobut.logger.Logger;

import java.util.concurrent.TimeUnit;

import io.grpc.ManagedChannel;

/**
 * @author xiaosy
 * @create 2020/5/12
 * @Describe
 **/
public class OpenDoorService {
    private String host = BuildConfig.API_FORMAL ? "yshapi.jrjkg.com.cn" : BuildConfig.JOYLIFE_GRPC_SERIVER_URL;
    private String port = BuildConfig.API_FORMAL ? "41233" : "21233";

    private static class SingleTonHolder {
        private static final OpenDoorService INSTANCE = new OpenDoorService();
    }


    private OpenDoorService() {

    }

    public static OpenDoorService getInstance() {
        return SingleTonHolder.INSTANCE;
    }

    /**
     * 获取AuthStub  设置超时时间  8秒
     *
     * @param channel
     * @return
     */
    private ServiceQRCodePassGrpc.ServiceQRCodePassBlockingStub getStub(ManagedChannel channel) {
        return ServiceQRCodePassGrpc.newBlockingStub(channel)
                .withDeadlineAfter(ApiConfig.TIMEOUT_NETWORK, TimeUnit.SECONDS);

    }

    /**
     * 获取二维码
     * int64 sys_tenant_no = 2;    //小区编号
     * int32 isVisitor = 3;        //是否访客 1访客 2业主
     * int32 isPass = 4;
     * UserInfo user_info = 5;     //访客或者业主信息
     *
     * @param callBack
     * @return
     */
    public GrpcAsyncTask<String, Void, QRCodePassResp> getQrCodePass(
            final int sysTenantNo,
            final int isVisitor,
            final int isPass,
            final UserInfo userInfo,
            CallBack callBack) {
        return new GrpcAsyncTask<String, Void, QRCodePassResp>(callBack) {
            @Override
            protected QRCodePassResp doRequestData(ManagedChannel channel) {
                QRCodePassReq message = QRCodePassReq.newBuilder()
                        .setSysTenantNo(sysTenantNo)
                        .setIsVisitor(isVisitor)
                        .setIsPass(isPass)
                        .setUserInfo(userInfo)
                        .build();
                Logger.d(message);
                QRCodePassResp response = null;
                try {
                    response = getStub(channel).getQrCodePass(message);
                    Logger.d(response);
                } catch (Exception e) {
                    Logger.e(e, "getQrCodePass");
                }
                return response;
            }
        }.setHost(host).setPort(port).doExecute();
    }


}
